Skip to content

Usage & Billing Hub v1 + v1.1 (aggregator /quota) - #967

Merged
dezren39 merged 4 commits into
mainfrom
feat/usage-billing-hub
Oct 26, 2026
Merged

dezren39 merged 4 commits into
mainfrom
feat/usage-billing-hub

Conversation

@dezren39

@dezren39 dezren39 commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Builds the Usage & Billing Hub per the approved design (hub-design-2026-10-25.md, goal usage-billing-hub-token-quotas-per-service-saas-limits; all §6 defaults Q2–Q8 as approved). The quota page evolves in place — route stays /quota, manifest entry retitled Usage & billing.

v1 — the hub page

  • Layout (§1.1): needs-attention strip → token-quota pool cards (existing extractors, unchanged) + PAYG dollars card → SaaS & services grouped per §1.4 → charges-this-period strip.
  • Bubble rules (GOAL.md-fixed): any metric >80% of its limit, or projected unbilled PAYG >$5 (unbilled accrual only, Q3), worst first across both families; empty state reads "nothing over threshold".
  • src/saas-extract.ts parses quota-view.md Part (b) with quota-extract's fail-soft dated-read pattern: per-service highlight metrics (the §2.2 † set), Decision-004 PAYG estimates (low/high recorded; 1.2 × high counted on cards, range on detail), charges evidence, renewal-only subscriptions strip. Missing patterns → identity shells, never invented numbers.
  • PAYG card (§1.2): Meta $23.92 accrued / $23.91 collected (Oct 19–25 console read); Cloudflare gateway accrual shown as the $29.60/$45.10 estimate pair (Nov 2 invoice authoritative), counted $54.12; Cloudflare platform excess estimate counted $6.24.
  • Freshness everywhere: measured-at + source class on every card; stale cards (past their §2 cadence) dim with an "as of" badge. Conflicts are shown, not resolved — a marker links to the dated history on the detail page.
  • /api/quota.json extended, not replaced: saas/payg/charges/attention/domains/subscriptions keys added; pools/burn/choices byte-identical for existing consumers (quota-guidance).
  • Feed: the collector embeds the hub sections (rides the existing fleet feed, §2.3); the live source falls back to a direct quota-view + registry read on older feeds, then fixtures.

v1.1 — detail + trends (§1.5)

  • /quota/service/<id> + /api/quota/service.json?id=: full metric list (incl. the Cloudflare long tail — 22 metrics), snapshot history charts with reset markers, pace projections where history supports them, all dated source reads, recorded conflicts, PAYG range detail.

Snapshot store (§4)

  • src/snapshots.ts: append-only, one JSONL file per month beside the comments/registry stores (PM_AGG_SNAPSHOTS_DIR), dedupe on re-append, original timestamps + source classes preserved; estimates stored as low/high usd-est pairs — the 1.2× rule applies at render.
  • scripts/backfill-usage-snapshots.ts: one-shot seed from quota-view.md + provider-quota-registry.md dated observations — 31 records, 2026-10-20 → 2026-10-25, 0 unmatched patterns, idempotent re-run. (The ¥44.63 DeepSeek balance is deliberately excluded: the §4 unit enum has no CNY and recording it as USD would corrupt history.)

Design decisions / deviations

  • Backblaze B2 omitted (no account, §1.4); Fly.io/Baseten omitted (unheld candidates, no meter, no renewal date). OCI is the §1.4 placeholder card.
  • measuredAt comes from each section's own Last checked record — the freshest date anywhere in a section can be a future operational date (Turso's 2026-10-29 mirror review), not a read.
  • Pool cards keep their existing rendering (their notes already carry the dated reads; the facet's freshness rides in provenance). Full per-card stamps apply to all hub-native cards (SaaS, PAYG).
  • GitHub Actions highlight = billable minutes (limit known, no billable volume recorded); the 3,079 comped October minutes are a separate detail metric — comped minutes do not consume the plan, so they do not bubble.

Verification

  • bunx tsc --noEmit — clean.
  • bun test — 102 pass / 0 fail (20 new in test/usage.test.ts; boot.test.ts quota assertion follows the retitle). Full suite re-run after merging current main.
  • Live runs (server actually executed, three configurations):
    • fixtures: /quota, /api/quota.json, /quota/service/turso, service twin all 200; strip, PAYG card, charges, pace + chart render.
    • live, no feed (direct-read fallback): 8 services extracted from the real quota-view.md (Cloudflare 22 metrics), 3 PAYG lines, 4 charge rows (Meta $20.00 + $3.91 on Visa •7535, ClinePass $82.52, unconfirmed $16.46), correct measured-at dates per service.
    • live, collector feed (collect-fleet-feed.ts → feed with hub sections + 40-domain dns): real pools, domains summary $606.70/yr, provenance live (fleet feed …), Cloudflare detail shows history chart + conflicts + dated reads against the backfilled store.

Follow-ups (not in this PR)

  • Writers (§4 b/c): stewardship-cycle appends after each quota-view refresh; keeper check-usage appends instead of overwriting; FFC appends on new feed values.
  • Deploy to the laptop aggregator + run the backfill against its store (PM_AGG_SNAPSHOTS_DIR), then confirm the tailnet page.
  • Q7 (fold the Meta PAYG Gmail watch into stewardship-cycle) and Q8 (weekly console-reads block) are cron-body changes, owned by the stewardship side.
  • v2 live collectors (Cloudflare analytics, Turso API route, Supabase mgmt scope, Vercel, GitHub billing token) per §5.

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

Archer added 4 commits October 26, 2026 13:08
Model + Source.usage() for the hub (design 2026-10-25): family-2
SaasService/PaygLine/ChargeRow/AttentionFlag/SnapshotRecord types,
Provenance gains a usage facet. New saas-extract.ts parses
quota-view.md Part (b) with quota-extract's fail-soft dated-read
pattern (per-service highlight metrics per design §2.2, Decision-004
PAYG estimates, charges evidence, renewal-only subscriptions strip).
New snapshots.ts: the §4 append-only store — monthly JSONL files,
dedupe on re-append, original timestamps/source classes preserved.
Bubble rules (>80% of limit, >$5 projected unbilled), freshness, and
pace projection derivations in derive.ts. Collector embeds saas/payg/
charges/subscriptions sections into the fleet feed; the live source
falls back to a direct quota-view+registry read, then fixtures.
Manifest: quota page retitled 'Usage & billing', route unchanged.
/quota becomes the hub (design §1.1): needs-attention strip (bubble
rules across both families), token-quota pool cards as before, the
PAYG dollars card (counted figures per Decision 004, ranges on the
detail view), family-2 SaaS cards grouped per §1.4 with highlight
metrics only, domains summary card linking /dns (never forking the
register), the renewal-only subscriptions strip, and the charges
evidence strip. Every card carries a measured-at + source stamp;
cards past their cadence dim with a stale badge. Conflicts render as
a marker linking to the dated history on the detail page.

v1.1 (§1.5): /quota/service/<id> + /api/quota/service.json?id= —
full metric list (incl. the Cloudflare long tail), snapshot history
charts with reset markers, pace projections where history supports
them, all dated source reads, and recorded conflicts.
/api/quota.json gains saas/payg/charges/attention/domains/
subscriptions keys; pools/burn/choices are unchanged.
scripts/backfill-usage-snapshots.ts seeds the §4 store from
quota-view.md + provider-quota-registry.md dated observations
(31 records, 2026-10-20 → 2026-10-25, original dates + source
classes kept; idempotent via store dedupe; the ¥ DeepSeek balance
is deliberately excluded — the §4 unit enum has no CNY).

test/usage.test.ts (20 tests): Part (b) extraction pinned to the
real phrasing, PAYG/charges evidence, bubble-rule edges (exactly
80% / exactly $5 do not bubble), store round-trip + dedupe, pace
projection across a reset boundary, freshness, hub + detail
renders. boot.test.ts: the quota-page assertion follows the
retitle. Fixes from live runs: measuredAt comes from each
section's Last-checked record (a future operational date in the
section is not a read), PAYG estimate notes strip their bold
label cleanly, freshness ages date-only stamps by calendar day.
@dezren39
dezren39 requested a review from a team as a code owner October 26, 2026 13:19
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T13:22:23.328975Z 493363b PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 26, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 56 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ae3f5a90-f9b7-4f08-b26d-5af08f30194e
Commits

Reviewing files that changed from the base of the PR and between aa0d6d1 and 493363b.

Files selected for processing: 18
  • pm-stack/aggregator/README.md
  • pm-stack/aggregator/scripts/backfill-usage-snapshots.ts
  • pm-stack/aggregator/scripts/collect-fleet-feed.ts
  • pm-stack/aggregator/src/config.ts
  • pm-stack/aggregator/src/derive.ts
  • pm-stack/aggregator/src/feed.ts
  • pm-stack/aggregator/src/model.ts
  • pm-stack/aggregator/src/pages.ts
  • pm-stack/aggregator/src/quota-extract.ts
  • pm-stack/aggregator/src/render.ts
  • pm-stack/aggregator/src/saas-extract.ts
  • pm-stack/aggregator/src/server.ts
  • pm-stack/aggregator/src/snapshots.ts
  • pm-stack/aggregator/src/source.ts
  • pm-stack/aggregator/src/sources/fixtures.ts
  • pm-stack/aggregator/src/sources/live.ts
  • pm-stack/aggregator/test/boot.test.ts
  • pm-stack/aggregator/test/usage.test.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 493363b2ee

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

export function projectPace(records: SnapshotRecord[], metricId: string): PaceProjection | null {
const recs = records
.filter((r) => r.metricId === metricId && r.unit === "pct" && typeof r.value === "number")
.sort((a, b) => a.ts.localeCompare(b.ts));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Sort snapshot timestamps by instant rather than string

When snapshot history mixes UTC timestamps and CDT offsets—as the new backfill script does with dayTs() and cdt()—lexicographic ordering is not chronological. For example, readings of 10 at 2026-10-24T12:00:00Z, 40 at 2026-10-25T12:00:00Z, and 80 at 2026-10-25T09:17:00-05:00 are sorted as 10, 80, 40. This makes projectPace() return null for increasing usage and makes resetMarkers() invent a reset; the same ordering in the snapshot store and chart renderer also corrupts history display. Compare parsed timestamps consistently across these functions instead.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant